import {
  getSourceDiyTable,
  syncDiyTableMetadata,
  checkTargetTableExists,
  createTableInTarget,
  syncTableDataOnce,
  compareAndSyncTableSchema,
} from "../utils/db-sync-utils.js";

import { syncSysMenu } from "../utils/sys_menu-sync.js";
import { syncDiyField } from "../utils/diy_field-sync.js";

export async function migrateTableTransaction(sourceConn, targetConn, tableName, removeField = false) {
  const targetTx = await targetConn.getConnection();
  try {
    await targetTx.beginTransaction();

    // 1. 同步 diy_table
    const sourceTable = await getSourceDiyTable(sourceConn, tableName);
    const diyTable = await syncDiyTableMetadata(sourceConn, targetTx, sourceTable, tableName);
    console.log(`✅ 已同步 diy_table: ${diyTable.Name}`);

    // 2. 同步 sys_menu
    const sysMenu = await syncSysMenu(sourceConn, targetTx, diyTable);
    console.log(`✅ 已同步 sys_menu`);

    // 3. 同步 diy_field
    const diyFields = await syncDiyField(sourceConn, targetTx, diyTable);
    console.log(`✅ 已同步 diy_field`);

    // 4. 同步表结构和数据
    const exists = await checkTargetTableExists(targetTx, tableName);
    if (!exists) {
      await createTableInTarget(sourceConn, targetTx, tableName);
      await syncTableDataOnce(sourceConn, targetTx, tableName, removeField);
    } else {
      await compareAndSyncTableSchema(sourceConn, targetTx, tableName);
      await syncTableDataOnce(sourceConn, targetTx, tableName, removeField);
    }

    await targetTx.commit();

    return {
      success: true,
      message: `已事务同步 ${tableName}`,
      diyTable,
      sysMenu,
      diyFieldsCount: diyFields.length,
    };
  } catch (err) {
    await targetTx.rollback();
    console.error(`❌ 事务回滚: ${err.message}`);
    throw new Error(`事务同步失败: ${err.message}`);
  } finally {
    await targetTx.release();
  }
}
